package com.jinghangzz.shop.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import org.springframework.stereotype.Component;

/**
 * 文件工具类
 * @author TeaBig
 */
@Component("fileUtil")
public class FileUtil
{
	/**
	 * 读取一个配置文件的内容
	 * @return
	 */
	public String readFile(InputStream is)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--readFile--");
		StringBuffer sb = new StringBuffer();
		try
		{
			/* 读取的是一个文本文件 */
			BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			String line = "" ; 
			while(( line = br.readLine()) != null)
			{
				sb.append(line);
			}
		} catch (IOException e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("读取文件失败了",e);
		} finally
		{
			try
			{
				if( is != null)
				{
					is.close();
					is = null ;
				}
			} catch (IOException e)
			{
				ConstatFinalUtil.SYS_LOGGER.error("关闭文件失败了",e);
			}
		}
		return sb.toString() ; 
	}
	
	/**
	 * 拷贝
	 * @param is
	 * @param os
	 * @return
	 */
	public boolean copy(InputStream is , OutputStream os)
	{
		/* 管子加粗 */
		BufferedInputStream bis = new BufferedInputStream(is);
		BufferedOutputStream bos = new BufferedOutputStream(os);
		try
		{
			/* 5m */
			byte[] b = new byte[1024 * 1024 * 5 ];
			/* 字节数组中使用了多少个字节 */
			int len = 0 ; 
			while(( len = bis.read(b) ) != -1)
			{
				bos.write(b, 0, len);
			}
			return true ; 
		} catch (IOException e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("拷贝文件失败了",e);
		} finally
		{
			try
			{
				if( bis != null)
				{
					bis.close();
					bis = null ;
				}
			} catch (IOException e)
			{
				ConstatFinalUtil.SYS_LOGGER.error("关闭文件失败了",e);
			}
			
			try
			{
				if( bos != null)
				{
					bos.close();
					bos = null ;
				}
			} catch (IOException e)
			{
				ConstatFinalUtil.SYS_LOGGER.error("关闭文件失败了",e);
			}
		}
		return false ; 
	}
}
